package com.quanyan.club.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.resp.ClubMemberAccountStreamInfo;
import com.quanyan.club.entity.vo.resp.RespClubActivity;
import com.quanyan.club.entity.vo.resp.RespClubActivityMember;
import com.quanyan.club.entity.vo.resp.RespIMActivityMember;
import com.quanyan.club.mapper.*;
import com.quanyan.club.service.*;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.BaseEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.orderpay.request.ReqOrderCancel;
import com.quanyan.orderpay.request.ReqOrderRefund;
import com.quanyan.orderpay.request.ReqRefundPayInfo;
import com.quanyan.orderpay.request.ReqRefundProduct;
import com.quanyan.orderpay.response.mq.OrderCallBackMsg;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.enums.PayWayEnum;
import com.quanyan.pay.enums.RefundStatusEnum;
import com.quanyan.user.response.RespOpenUserInterest;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by yue.yuan on 2016/11/29.
 */
@Service("activityAccountService")
public class ActivityAccountServiceImpl extends BaseServiceImpl implements ActivityAccountService {

    private static final Logger logger = LoggerFactory.getLogger(ActivityAccountServiceImpl.class);

    @Autowired
    private TbSignUserMapper tbSignUserMapper;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private ClubActivityMapper clubActivityMapper;
    @Autowired
    private TbClubActivityMapper tbClubActivityMapper;
    @Autowired
    private TbActivityMapper tbActivityMapper;
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private ClubAccountService clubAccountService;
    @Autowired
    private TbOrderRefundMapper tbOrderRefundMapper;
    @Autowired
    private ActivityCallBackService activityCallBackService;
    @Autowired
    @Qualifier("activityOrderPayRelatedClient")
    private QcMsgClient activityOrderPayRelatedClientImpl;
    @Autowired
    private ActivitySupportService activitySupportService;

    public BigDecimal activityAccountOnline(int activityId)
    {
        //该活动已支付的订单
        TbOrderExample orderExampler = new TbOrderExample();
        orderExampler.createCriteria().andCancelTypeEqualTo(Constants.BYTE_ZERO)
                .andOrderStatusIn(Arrays.asList((byte)2,(byte)6,(byte)7))
                .andActivityIdEqualTo(activityId)
                .andIsDeleteEqualTo(Constants.BYTE_ZERO);
        List<TbOrder> orders = tbOrderMapper.selectByExample(orderExampler);
        BigDecimal totalAmount = BigDecimal.ZERO;
        if(null == orders || orders.size() == 0)
        {
            return totalAmount;
        }
        for(TbOrder order : orders)
        {
            if(null != order && null != order.getPayAmount())
            {
                totalAmount = totalAmount.add(order.getOrderAmount());
            }
        }
        return totalAmount;
    }

    public APIResponse<RespIMActivityMember> getActivityMemberListIM(Integer activityId,
                                                                      Integer uid)
    {
        RespIMActivityMember respIMActivityMember = new RespIMActivityMember();
        if(null != uid)
        {
            TbSignUserExample signUserExample = new TbSignUserExample();
            signUserExample.createCriteria().andStatusEqualTo(1)
                    .andIsCancelEqualTo(0)
                    .andActivityIdEqualTo(activityId)
                    .andOrderUserIdEqualTo(uid);
            int signCount = tbSignUserMapper.countByExample(signUserExample);
            TbClubActivityExample clubActivityExample = new TbClubActivityExample();
            clubActivityExample.createCriteria().andActivityIdEqualTo(activityId).andUidEqualTo(uid);
            int count = tbClubActivityMapper.countByExample(clubActivityExample);
            TbOrderExample orderExample = new TbOrderExample();
            orderExample.createCriteria()
                    .andActivityIdEqualTo(activityId)
                    .andOrderUidEqualTo(uid).andOrderStatusEqualTo(Constants.BYTE_ONE);
            int orderStatus = tbOrderMapper.countByExample(orderExample);
            if(count > 0 || (signCount > 0 && orderStatus != 1))
            {
                TbActivity tbActivity = tbActivityMapper.selectByPrimaryKey(activityId);
                respIMActivityMember.setActivityName(tbActivity.getName());
                respIMActivityMember.setActivityId(tbActivity.getId());
                respIMActivityMember.setGroupId(tbActivity.getGroupId());
                Integer plannerUid = clubActivityMapper.selectUidByActivityId(activityId);
                respIMActivityMember.setPlannerUid(plannerUid);
            }
        }
        APIResponse<List<RespClubActivityMember>> memberResp = getActivityMemberList(activityId,uid);
        List<RespClubActivityMember> members = new ArrayList<RespClubActivityMember>();
        if(null != memberResp.getData() && memberResp.getData().size() > 0)
        {
            members = memberResp.getData();
        }else {
            return APIResponse.returnFail("这个活动没有人报名哦！");
        }
        respIMActivityMember.setRespClubActivityMembers(members);
        return APIResponse.returnSuccess(respIMActivityMember);
    }

    public APIResponse<List<RespClubActivityMember>> getActivityMemberList(Integer activityId,
                                                                           Integer uid) {
        Integer clubId = clubActivityMapper.selectClubByActivityId(activityId);
        if(null == clubId || clubId <= 0)
        {
            return APIResponse.returnFail("没有对应的俱乐部,活动ID：" + activityId);
        }
        boolean isAdmin = false;
        if(null != uid)
        {
            if(clubMemberService.isClubAdminMember(uid, clubId))
            {
                isAdmin = true;
            }
        }
        List<RespClubActivityMember> resp = buildClubActivityMember(uid,
                activityId, clubId, false, isAdmin);
        if (CollectionUtils.isEmpty(resp)) {
            return APIResponse.returnFail("这个活动没有人报名哦！");
        }
        return APIResponse.returnSuccess(resp);
    }


    public List<RespClubActivityMember> buildClubActivityMember(Integer uid,
                                                                Integer activityId,
                                                                int clubId,
                                                                boolean isBusiness,
                                                                boolean isAdmin) {

        TbSignUserExample tbSignUserExample = new TbSignUserExample();
        tbSignUserExample.createCriteria()
                .andActivityIdEqualTo(activityId).andOrderIdIsNotNull()
                .andStatusEqualTo(1).andIsCancelEqualTo(0);//有效
        tbSignUserExample.setLimit(Limit.buildLimit(1, Integer.MAX_VALUE));
        List<TbSignUser> tbSignUsers = tbSignUserMapper.selectByExample(tbSignUserExample);
        if (CollectionUtils.isEmpty(tbSignUsers)) {
            return null;
        }
        List<Byte> orderStatus = new ArrayList<Byte>();
        orderStatus.add(Constants.BYTE_TWO);
        orderStatus.add((byte) 7);
        orderStatus.add((byte) 6);
        orderStatus.add(Constants.BYTE_ONE);
        List<Integer> userIds = Lists.newArrayList();
        for (TbSignUser user : tbSignUsers) {
            if (user.getOrderUserId() != null) {
                userIds.add(user.getOrderUserId());
            }
        }
        //批量查询用户信息
        //APP3.0需求 获取成员备注
        logger.warn("调用用户中心，入参:{}", userIds);
        APIResponse<List<RespUserInfoDetail>> respUserInfoBase = null;
        if(null == uid)
        {
            respUserInfoBase = userServiceFacade.batchQueryUserInfoDetail(userIds);
        }
        else {
            respUserInfoBase =
                    userServiceFacade.batchQueryUserInfoDetail(uid, userIds);
        }
        List<RespUserInfoDetail> respUserInfoBases = new ArrayList<RespUserInfoDetail>();
        if (respUserInfoBase.isRet()) {
            respUserInfoBases = respUserInfoBase.getData();
        }
        Map<Integer, List<RespOpenUserInterest>> integerListMap =
                userServiceFacade.batchQueryUserInterest(userIds);
        Map<Integer, RespUserInfoDetail> userIdAndInfo = Maps.newHashMap();
        for (RespUserInfoDetail userInfo : respUserInfoBases) {
            if (null != userInfo) {
                userIdAndInfo.put(userInfo.getUid(), userInfo);
            }
        }

        List<RespClubActivityMember> retList = Lists.newArrayList();

        for (TbSignUser user : tbSignUsers) {
            RespClubActivityMember mainMember = new RespClubActivityMember();
            if (user.getIsReplace().intValue() == 1
                    || user.getOrderId() == null) {
                continue;//补报名人没有订单
            }
            if(user.getManageType() != 2)
            {
                TbOrder order = tbOrderMapper.selectByPrimaryKey(user.getOrderId());
                if (null == order) {
                    continue;
                }
                if(!orderStatus.contains(order.getOrderStatus()))
                {
                    continue;
                }
                if(order.getOrderStatus().equals(Constants.BYTE_ONE))
                {
                    mainMember.setOrderStatus(1);
                }
            }

            List<RespClubActivityMember> replaceMembers = Lists.newArrayList();
            for (TbSignUser userTwice : tbSignUsers) {
                RespClubActivityMember replaceMember = new RespClubActivityMember();
                if (userTwice.getOrderId() == null) {
                    continue;//补报名人没有订单
                }
                if (userTwice.getIsReplace().intValue() != 1) {
                    continue;//代报名
                }
                if (userTwice.getOrderId().intValue() != user.getOrderId().intValue()) {
                    continue;//订单号是同一单
                }
                replaceMember.setName(userTwice.getName());
                replaceMember.setGender(userTwice.getGender());
                replaceMembers.add(replaceMember);//是当前这个付款人的代报名
            }
            List<String> interests = new ArrayList<String>();
            if (null != integerListMap.get(user.getOrderUserId())) {
                List<RespOpenUserInterest> list = integerListMap.get(user.getOrderUserId());
                if (null != list && list.size() > 0) {
                    for (RespOpenUserInterest interest : list) {
                        if (null == interest) {
                            continue;
                        }
                        interests.add(interest.getName());
                    }
                }
            }
            //APP12月底需求 B端成员列表
            mainMember.setSignUpTime(user.getCreateTime());
            if(clubMemberService.isClubMember(user.getOrderUserId(), clubId))
            {
                mainMember.setIsMember(1);
            }
            //APP3.0需求 成员列表增加返回手机号
            if(isAdmin)
            {
                mainMember.setMobile(user.getMobile());
            }
            //APP3.0需求 成员列表增加返回备注
            mainMember.setFriendRemark(userIdAndInfo.get(user.getOrderUserId()).getFriendRemarks());
            mainMember.setInterests(interests);
            mainMember.setName(user.getName());
            mainMember.setGender(user.getGender());
            mainMember.setUid(user.getOrderUserId());
            mainMember.setLevel(userIdAndInfo.get(user.getOrderUserId()).getLevelDe());
            mainMember.setIcon(userIdAndInfo.get(user.getOrderUserId()).getIcon());
            mainMember.setReplaceMembers(replaceMembers);
            retList.add(mainMember);
        }
        if(null == retList)
        {
            return new ArrayList<RespClubActivityMember>();
        }
        return retList;
    }

    /**
     * 处理订单退款
     */
    public boolean processRefundOrderActivity(RespClubActivity respClubActivity, Integer activityId, String reason,
                                              Integer uid, Byte refundType) {
        //线上所有订单状态更改为创办人取消
        TbOrderExample orderExample = new TbOrderExample();
        TbOrderExample.Criteria orderCriteria = orderExample.createCriteria();
        orderCriteria.andActivityIdEqualTo(activityId);
        TbOrder o = new TbOrder();
        o.setCancelType((byte) 2);
        tbOrderMapper.updateByExampleSelective(o, orderExample);

        //线上订单
        orderCriteria.andActivityIdEqualTo(activityId);
        if (null != uid) {
            orderCriteria.andOrderUidEqualTo(uid);
        }
        orderCriteria.andOrderStatusEqualTo(Constants.BYTE_TWO);//支付成功
        List<TbOrder> orderList = tbOrderMapper.selectByExample(orderExample);

        if (CollectionUtils.isEmpty(orderList)) {
            return true;
        }

        try {
            for (TbOrder tbOrder : orderList) {
                logger.warn("订单取消退款，订单号：" + tbOrder.getOrderNo());


                //如果只有余额，则退俱乐部余额到线上账户
                if (tbOrder.getPayAmount().doubleValue() == 0
                        && tbOrder.getAccumulateAmount() == 0) {
                    logger.warn("没有第三方支付和鸟蛋支付，不调支付系统退款，直接退俱乐部抵扣余额");
                    //4. 更新订单状态
                    tbOrder.setOrderStatus((byte) 4); //退款中
                    tbOrder.setCancelType((byte) 2); //0 未取消,  取消对象: 1 用户主动取消 2活动创办人取消 3活动异常百灵鸟官方后台管理员取消 4活动未达到开启条件而取消
                    tbOrderMapper.updateByPrimaryKeySelective(tbOrder);

                    boolean isret = activityCallBackService.cancelOrderNotifyCallback(tbOrder.getOrderNo());
                    if (!isret) {
                        logger.warn("直接退俱乐部抵扣余额，失败");
                        throw new BizException("直接退俱乐部抵扣余额，失败");
                    }

                    //4. 更新订单状态
                    tbOrder.setOrderStatus((byte) 5); //退款完成
                    tbOrder.setCancelType((byte) 2); //0 未取消,  取消对象: 1 用户主动取消 2活动创办人取消 3活动异常百灵鸟官方后台管理员取消 4活动未达到开启条件而取消
                    tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
                }
                //cppService.pushCancelActivityToMember(respClubActivity, tbOrder.getOrderNo());

                //2、退积分和第三方
                String refundOrderNo = CommonUtils.generateOrderNo(tbOrder.getOrderUid());
                if ((tbOrder.getAccumulateAmount() == null
                        || tbOrder.getAccumulateAmount().doubleValue() <= 0)
                        && (tbOrder.getPayAmount() == null
                        || tbOrder.getPayAmount().doubleValue() <= 0)) {

                    tbOrder.setCancelType((byte) 2);
                    tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
                } else {
                    APIRequest apiRequest = setRefundOrderParam(tbOrder, refundOrderNo, reason);//组装退款所需参数
                    logger.warn("调用支付系统退款：" + JSONObject.toJSONString(apiRequest));
                    APIResponse<RefundStatusEnum> enumAPIResponse = orderPayService.refundApply(apiRequest);//调用支付系统退款
                    if (enumAPIResponse.isRet()) {//申请退款成功
                        //退款申请记录
                        insertOrderRefund(
                                tbOrder.getPayAmount(),
                                tbOrder.getId(),
                                tbOrder.getPayType(),
                                tbOrder.getOrderUid(),
                                reason, refundType,
                                refundOrderNo);
                        //修改订单状态//1待支付 2支付成功 3支付失败 4退款中 5退款完成 6:AA退款完成 7已评价
                        //0 未取消,  取消对象: 1 用户主动取消 2活动创办人取消 3活动异常百灵鸟官方后台管理员取消
                        tbOrder.setOrderStatus((byte) 4);
                        tbOrder.setCancelType((byte) 2);
                        tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
                    }
                }
            }
            return true;
        } catch (Exception e) {
            logger.warn("退款申请失败，活动编号：" + activityId);
            logger.warn(e.getMessage());
            return false;
        }
    }

    public boolean insertOrderRefund(BigDecimal amount,
                                     Integer orderId,
                                     Byte payId,
                                     Integer uid,
                                     String reason, Byte refundType,
                                     String refundOrderNo) {
        TbOrderRefund tbOrderRefund = new TbOrderRefund();
        tbOrderRefund.setReason(reason);
        tbOrderRefund.setAmount(amount);
        tbOrderRefund.setRefundUid(uid);
        tbOrderRefund.setAudit((byte) 0);
        tbOrderRefund.setOrderId(orderId);
        tbOrderRefund.setPayId(payId);
        tbOrderRefund.setState((byte) 0);
        tbOrderRefund.setAudit((byte) 0);
        tbOrderRefund.setRefundType(refundType);
        tbOrderRefund.setRefundOrderNo(refundOrderNo);
        int count = tbOrderRefundMapper.insertSelective(tbOrderRefund);

        if (count <= 0) {
            logger.warn("退款记录生成失败:" + JSONObject.toJSONString(tbOrderRefund));
            return false;
        }
        logger.warn("退款记录生成成功:" + JSONObject.toJSONString(tbOrderRefund));
        return true;
    }

    public void refundBalanceAmount(TbOrder order, String activityName, int clubId) {
        //2. 将抵扣的俱乐部余额退回到俱乐部成员账户
        ClubMemberAccountStreamInfo info =
                clubAccountService.addOrDeductionPersonClubAccountBalance(
                        order.getBalanceAmount(), order.getOrderUid(), clubId, true);
        logger.warn("2 退回抵扣余额，" + order.getBalanceAmount() + "，返回："
                + JSON.toJSONString(info));
        if (null == info) {
            throw new BizException("退回抵扣金额失败！");
        }
        //记录个人账户流水
        clubAccountService.recordPersonClubAccountDeductibleStream(
                order.getOrderUid(),
                order.getActivityId(),
                activityName + "报名费退款",
                order.getPayType(), clubId,
                info,
                order.getOrderTradeNo(), (byte) 2, (byte) 1);
    }

    /**
     * 组装退款所需参数
     */
    public APIRequest setRefundOrderParam(TbOrder tbOrder,
                                          String refundOrderNo,
                                          String reason) {
        //支付信息 包含积分、第三方支付
        List<ReqRefundPayInfo> payInfoList = new ArrayList<>();

        if (tbOrder.getAccumulateAmount() != null
                && tbOrder.getAccumulateAmount().doubleValue() > 0) {
            ReqRefundPayInfo reqRefundAccumulateInfo = new ReqRefundPayInfo();
            reqRefundAccumulateInfo.setPayId(PayWayEnum.PAY_WAY_FOR_AGES.getPayId());
            reqRefundAccumulateInfo.setRefundAmount(BigDecimal.valueOf(tbOrder.getAccumulateAmount()));
            payInfoList.add(reqRefundAccumulateInfo);
        }

        if (tbOrder.getPayAmount() != null
                && tbOrder.getPayAmount().doubleValue() > 0) {
            ReqRefundPayInfo reqRefundPayInfo = new ReqRefundPayInfo();
            reqRefundPayInfo.setPayId(tbOrder.getPayType().intValue());
            reqRefundPayInfo.setRefundAmount(tbOrder.getPayAmount());
            payInfoList.add(reqRefundPayInfo);
        }

        //商品信息
        List<ReqRefundProduct> reqRefundProductList = new ArrayList<>();
        ReqRefundProduct reqRefundProduct = new ReqRefundProduct();
        reqRefundProduct.setProductId(tbOrder.getActivityId() + "");
        reqRefundProductList.add(reqRefundProduct);

        ReqOrderRefund reqOrderRefund = new ReqOrderRefund();
        reqOrderRefund.setOrderNo(tbOrder.getOrderTradeNo());
        reqOrderRefund.setNeedAudit(false);
        reqOrderRefund.setOutTradeNo(tbOrder.getOrderNo());
        reqOrderRefund.setOutTradeRefundNo(refundOrderNo);
        reqOrderRefund.setReason(reason);

        reqOrderRefund.setUid(tbOrder.getOrderUid());
        reqOrderRefund.setSourceBusinessId(Constants.CLUB_ACTIVITY_REFUND_ORDER_BUSINESS_CODE);
        reqOrderRefund.setSourceSystemId(Constants.CLUB_SYSTEM_CODE);
        reqOrderRefund.setReqRefundPayInfos(payInfoList);
        reqOrderRefund.setRefundProductList(reqRefundProductList);
        APIRequest apiRequest = new APIRequest();
        apiRequest.setData(reqOrderRefund);
        return apiRequest;
    }

    public void beforeRefundOrder(List<TbSignUser> signUsers,
                                  RespClubActivity respClubActivity, TbOrder tbOrder,
                                         int signStatus, int type)
    {
        int activityId = respClubActivity.getActivityId();
        TbSignUserExample signUserExample = new TbSignUserExample();
        signUserExample.createCriteria()
                .andActivityIdEqualTo(activityId) //活动id
                .andOrderIdEqualTo(tbOrder.getId())
                .andStatusEqualTo((int) Constants.BYTE_ONE);        //有效的
        int minusCounts = tbSignUserMapper.countByExample(signUserExample);
        logger.warn("更新活动已报名人数，activityId:" + activityId + "，count = " + signUsers.size());
        Map<String, Object> paraMap = Maps.newHashMap();
        paraMap.put("activityId", activityId);
        paraMap.put("type", type);
        paraMap.put("totalCount", minusCounts);
        logger.warn("恢复活动报名：" + JSON.toJSONString(paraMap));
        int affectTotalCount = clubActivityMapper.recoveryLockSignTotalNum(paraMap);
        if (affectTotalCount <= 0) {
            logger.warn("恢复活动报名总人数库存失败");

            throw new BizException(ApiResponseEnum.INTERNAL_ERROR);
        }
        //扣除响应人数
        //clubActivityMapper.deductionSignTotalNum(paraMap);要删掉,增加到上面
        //4. 更新报名人报名记录表
        TbSignUserExample signUserExampleUpdate = new TbSignUserExample();
        signUserExampleUpdate.createCriteria()
                .andActivityIdEqualTo(activityId)
                .andOrderIdEqualTo(tbOrder.getId());
        TbSignUser updateSignUser = new TbSignUser();
        updateSignUser.setIsCancel(1);//取消
        updateSignUser.setStatus(signStatus);
        int updateSign = tbSignUserMapper.updateByExampleSelective(updateSignUser, signUserExampleUpdate);
        if(updateSign <= 0)
        {
            throw new BizException("取消订单恢复报名状态失败");
        }
    }


    public APIResponse refundOrder(TbOrder tbOrder,
                                   RespClubActivity respClubActivity,
                                   byte cancelType, byte orderStatus,
                                   String reason, byte refundType)
    {
        tbOrder.setCancelType(cancelType);
        tbOrder.setOrderStatus(orderStatus);//设置成已取消
        tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
        String refundOrderNo = CommonUtils.generateOrderNo(tbOrder.getOrderUid());//退款单号
        //1: 活动结算AA退款 2:用户取消已支付订单退款 3:活动发起人取消已支付订单退款 4:活动未达到开启条件,给已经报名支付成功的人退款 5现场管理人补请假退款
        this.insertOrderRefund(
                tbOrder.getPayAmount(),
                tbOrder.getId(),
                tbOrder.getPayType(),
                tbOrder.getOrderUid(), reason,
                refundType, refundOrderNo);

        //如果有俱乐部余额抵扣 , 则退回
        if (tbOrder.getBalanceAmount() != null && tbOrder.getBalanceAmount().doubleValue() > 0) {
            refundBalanceAmount(tbOrder, respClubActivity.getName(),
                    respClubActivity.getClubId());
            //5. 更新订单状态
            TbOrder updateOrder = new TbOrder();
            updateOrder.setId(tbOrder.getId());
            updateOrder.setOrderStatus((byte) 5); //用户取消，退款完成
            int ret = tbOrderMapper.updateByPrimaryKeySelective(updateOrder);
            logger.warn("5  更改订单状态为5（已退款），返回：" + ret);
            if (ret <= 0) {
                logger.warn("更新订单状态失败");
                throw new BizException(ApiResponseEnum.INTERNAL_ERROR);
            }
            activitySupportService.afterRefundActivity(respClubActivity,
                    tbOrder.getOrderUid(),tbOrder.getOrderNo(), tbOrder.getId());
        }else {

            APIRequest apiRequest = setRefundOrderParam(tbOrder, refundOrderNo, reason);//组装退款所需参数
            logger.warn("调用支付系统退款：" + JSONObject.toJSONString(apiRequest));
            APIResponse<RefundStatusEnum> enumAPIResponse = orderPayService.refundApply(apiRequest);//调用支付系统退款
            if (!enumAPIResponse.isRet()) {
                logger.warn("调用订单系统退款失败：" + enumAPIResponse.getErrmsg());
                throw new BizException(ApiResponseEnum.INTERNAL_ERROR);
            }
            OrderCallBackMsg orderCallBackMsg = new OrderCallBackMsg();
            orderCallBackMsg.setOrderNo(tbOrder.getOrderTradeNo());
            orderCallBackMsg.setType(OrderCallBackMsg.REFUND);
            orderCallBackMsg.setState(OrderCallBackMsg.SUCCESS);
            feedbackOrderSystemOrderStatus(orderCallBackMsg);
        }

        // 1 用户主动取消已支付订单(退款) 2活动创办人取消
        // 3活动异常百灵鸟官方后台管理员取消 4活动未达到开启条件而取消 5用户取消未支付订单'

        //调用支付系统关闭未支付订单
        closeOrder(tbOrder);
        return APIResponse.returnSuccess();
    }

    public void closeOrder(TbOrder tbOrder)
    {
        APIRequest<ReqOrderCancel> apiRequest = new APIRequest<ReqOrderCancel>();
        ReqOrderCancel reqOrderCancel = new ReqOrderCancel();
        reqOrderCancel.setSourceSystemId(Constants.CLUB_SYSTEM_CODE);
        reqOrderCancel.setSourceBusinessId(
                Constants.CLUB_ACTIVITY_ORDER_BUSINESS_CODE);
        reqOrderCancel.setOrderNo(tbOrder.getOrderTradeNo());
        reqOrderCancel.setOutTradeNo(tbOrder.getOrderNo());
        reqOrderCancel.setUid(tbOrder.getOrderUid());
        reqOrderCancel.setCancelReason("订单超时未支付");
        apiRequest.setData(reqOrderCancel);
        APIResponse<BaseEnum> apiResponse = orderPayService.orderCancel(apiRequest);
        if (!apiResponse.isRet()) {
            throw new BizException("调用支付系统取消未支付订单失败：" + apiResponse.getErrmsg());
        }
    }

    private void feedbackOrderSystemOrderStatus(OrderCallBackMsg orderCallBackMsg) {
        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        mqRequestMsg.setTopic(OrderPayService.TOPIC_ORDER_CALLBACK_NOTIFY);
        mqRequestMsg.setTag(Constants.ORDER_SYSTEM_CODE);
        mqRequestMsg.setMsgId(orderCallBackMsg.getOrderNo()); //订单号.
        mqRequestMsg.setFlag(0);
        mqRequestMsg.setBody(ObjectUtil.toByteArray(orderCallBackMsg));
        activityOrderPayRelatedClientImpl.asyncSend(mqRequestMsg);
    }
}
